package com.scalar.chiptrack.adaptor;

import java.util.Calendar;
import java.util.ArrayList;
import java.util.Properties;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;

import com.scalar.ScalarException;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;

import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.chiptrack.users.dao.NotificationSetupDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;

import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.BodyPart;

public final class AdaptorUtils implements AdaptorConstants
{

    // General
    private static final String LOG_LEVEL = "debug";
    private static final int MAX_LOG_FILE_SIZE = 1024 * 500;
    private static final int MAX_LOG_FILE_SIZE_JOB_HANDLER = 1024 * 500;
    private static final int ROTATING_LOG_FILE_COUNT = 1;

    // Adaptor
    private static final String ADAPTOR_LOG_FILE_NAME = "adaptor%u.log";
    private static final String ADAPTOR_LOG_PREFIX = "Adaptor";
    private static Logger adaptorLogger = null;

    // Data Interpreter
    private static final String DATA_PARSER_LOG_FILE_NAME = "data_parser%u.log";
    private static final String DATA_PARSER_LOG_PREFIX = "DataParser";
    private static Logger parserLogger = null;

     //WIPFED Adaptor
    private static final String WIPFED_ADAPTOR_LOG_FILE_NAME = "wipfed_adaptor%u.log";
    private static final String WIPFED_ADAPTOR_LOG_PREFIX = "wipFed.Adaptor";
    private static Logger wipFedAdaptorLogger = null;

    // WIPFED Data Interpreter
    private static final String WIPFED_DATA_PARSER_LOG_FILE_NAME = "wipfed_data_parser%u.log";
    private static final String WIPFED_DATA_PARSER_LOG_PREFIX = "wipFed.DataParser";
    private static Logger wipFedParserLogger = null;

    //Job Schedular
    private static final String JOB_SCHEDULING_LOG_FILE_NAME = "job_handler%u.log";
    private static final String JOB_SCHEDULING_LOG_PREFIX = "JOB.Handler";
    private static Logger jobHandlerLogger = null;

    public static final String FILE_EXTN_HTML = "html";
    public static final String FILE_EXTN_TXT = "txt";
    public static final String FILE_EXTN_CSV = "csv";
    public static final String FILE_EXTN_WSM = "wsm";
    public static final String FILE_EXTN_WAT = "wat";
    public static final String FILE_EXTN_QCI = "qci";
    public static final String FILE_EXTN_XLS = "xls";
    public static final String FILE_EXTN_ZIP = "zip";

    private static Calendar s_calendar = null;
    private static Logger s_logger = null;
    private static final String INBOX        = "INBOX";
    private static final String POP_MAIL     = "pop3";
    /**
     * Read and save data
     */
    public static String saveAsFile( BufferedReader reader, String dirString, String fileNameString, String extn ) throws Exception
    {
        return saveAsFile( reader, dirString, fileNameString, extn, true );
    }

    public static String saveAsFile( BufferedReader reader, String dirString, String fileNameString, String extn, boolean appendTimestamp ) throws Exception
    {

        if ( reader == null ) return "";

        FileWriter fileWriter = null;
        String umcOutputFile = null;

        try
        {
            File umcOutputDir = new File( dirString );

            // Create the directory if doesnt exist
            if ( umcOutputDir.exists() == false )
            {
                umcOutputDir.mkdirs();
            }

            String timeString = "";
            if ( appendTimestamp )
            {
                timeString = "_" + getTimeAsString();
            }

            umcOutputFile = umcOutputDir.getAbsolutePath() + "/" + fileNameString + timeString + "." + extn;
            fileWriter = new FileWriter( umcOutputFile, false );

            String line = null;
            while ( ( line = reader.readLine() ) != null )
            {
                //System.out.println("Line:"+line);
                fileWriter.write( line + LINE_SEPARATOR );
            }

            fileWriter.close();
            fileWriter = null;
        }
        finally
        {
            if ( fileWriter != null )
            {
                try
                {
                    fileWriter.close();
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return umcOutputFile;
    }

    // added by hareesh on 3rd January 2004
    public static void removeOldFiles( String dirString, Logger logger ) throws ScalarException
    {
        try
        {
            File outputDir = new File( dirString );
            if ( outputDir.exists() == false )
            {
                return;
            }

            String removeDirString = outputDir.getAbsolutePath() + "/removed";
            File removeDir = new File( removeDirString );

            if ( removeDir.exists() == false )
            {
                removeDir.mkdirs();
            }

            File[] oldFiles = outputDir.listFiles();
            int countOldFiles = oldFiles.length;

            if ( countOldFiles > 0 )
            {
                for ( int count = 0; count < countOldFiles; count++ )
                {
                    File removeFile = oldFiles[count];
                    if ( !removeFile.isDirectory() )
                    {
                        String removeFileName = removeFile.getName();
                        String sourcePath = removeFile.getAbsolutePath();
                        String destPath = removeDir.getAbsolutePath() + "/" + removeFileName;
                        AdaptorUtils.fileCopy( sourcePath, destPath );
                        removeFile.delete();
                        String message = "Moving File " + removeFileName + " to /remove folder";

                        if ( logger != null )
                        {
                            synchronized ( logger )
                            {
                                logger.logDebug( message + LINE_SEPARATOR );
                            }
                        }
                        else
                        {
                            System.out.println( message );
                        }
                    }
                }

                //To throw an Exception when the file is not deleted
                File[] removeFiles = outputDir.listFiles();
                int countRemovedFiles = removeFiles.length;
                String removeFileName = null;
                for ( int count = 0; count < countRemovedFiles; count++ )
                {
                    File removeFile = removeFiles[count];
                    if ( !removeFile.isDirectory() )
                    {
                        removeFileName = removeFile.getName();
                    }
                }
                if ( countRemovedFiles > 3 )
                {
                    throw new ScalarException( " File " + removeFileName + " Can't Delete from " + outputDir );
                }
            }
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            throw new ScalarException( "Exception occurred while deleting old files at Adaptor Directory " );
        }

        return;
    }

    //Added by Mallikarjun Ankati Jan 14th 2003
    public static String saveAsBinaryFile( BufferedInputStream biStream, String dirString, String fileNameString, String extn, boolean appendTimestamp ) throws Exception
    {

        if ( biStream == null ) return "";

        FileOutputStream fileStream = null;
        String umcOutputFile = null;

        try
        {
            File umcOutputDir = new File( dirString );

            //Create the directory if doesn't exist
            if ( umcOutputDir.exists() == false )
            {
                umcOutputDir.mkdirs();
            }

            String timeString = "";
            if ( appendTimestamp )
            {
                timeString = "_" + getTimeAsString();
            }

            umcOutputFile = umcOutputDir.getAbsolutePath() + "/" + fileNameString + timeString + "." + extn;
            fileStream = new FileOutputStream( umcOutputFile, false );

            int c;
            while ( ( c = biStream.read() ) != -1 )
            {
                fileStream.write( c );
            }

            fileStream.close();
            fileStream = null;
        }
        finally
        {
            if ( fileStream != null )
            {
                try
                {
                    fileStream.close();
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return umcOutputFile;

    }

    public static void binaryFileCopy( String sourceFile, String destFile ) throws IOException
    {

        if ( ( sourceFile == null ) || ( destFile == null ) )
        {
            return;
        }

        File inputFile = new File( sourceFile );
        File outputFile = new File( destFile );

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try
        {

            fis = new FileInputStream( inputFile );
            fos = new FileOutputStream( outputFile );
            byte[] buf = new byte[1024];
            int i = 0;
            while ( ( i = fis.read( buf ) ) != -1 )
            {
                fos.write( buf, 0, i );
            }
        }
        finally
        {
            if ( fis != null )
                try
                {
                    fis.close();
                }
                catch ( IOException ignore )
                {
                }
            if ( fos != null )
                try
                {
                    fos.close();
                }
                catch ( IOException ignore )
                {
                }
        }
    }

    // The scope of this method is to UNZIP the files for a given directory
    public static String fileUnZipping(String unzipFileName, String filePath, String extention)
    {
        byte[] databuff 	= new byte[2048];
        File file 		= new File( filePath );
        File files[] 	= file.listFiles();
        int lint_fileCount 		= files.length;

        BufferedOutputStream bos = null;
        FileInputStream fis      = null;
        ZipInputStream  zis      = null;
        FileOutputStream fos     = null;
        String unzipFile         = null;

        try
		{
            for( int i = 0; i < lint_fileCount; i++ )
			{
                if( ( files[i].getName().endsWith( ".zip" ) ) )
                {
                     if ( unzipFileName != null )
                     {
                        unzipFile = file.getAbsolutePath() + "/"+ unzipFileName + "_" + getTimeAsString() + "."+extention ;
                     }
                     else
                     {
                        unzipFile = file.getAbsolutePath() + "/"+ files[i].getName().substring(0, files[i].getName().indexOf(".") ) +  "."+extention ;
                     }
                     fis = new FileInputStream( files[i].getAbsolutePath() );
                     zis = new ZipInputStream(new BufferedInputStream( fis ) );
                     ZipEntry entry;
                     while( ( entry = zis.getNextEntry() ) != null )
                     {                         
                        if ( entry.getName() != null && entry.getName().trim().indexOf(".PDF") < 0 && entry.getName().trim().indexOf(".jpg") < 0  )
                        {
                            System.out.println("UnZipping: " + entry.getName() );    
                            int count;
                            // write the files
                            fos = new FileOutputStream( file.getAbsolutePath() + "/"+ entry.getName(), false );
                            bos = new BufferedOutputStream(fos, 2048);
                            while ((count = zis.read(databuff, 0, 2048)) != -1)
                            {
                                bos.write(databuff, 0, count);
                            }
                            bos.flush();
                            bos.close();
                            bos = null;
                            entry = null;
                        }
                     }
                     if ( fos != null )
                     {
                        fos.close();
                        fos = null;
                     }
                     zis.close();
                     zis = null;
                     fis.close();
                     fis = null;
                 }
			 }
        }
        catch(Exception e)
        {
             e.printStackTrace();
             System.out.println("Exception while UnZipping the file :"+e);
        }
        finally
        {
            if ( bos != null )
            {
                try
                {
                    bos.close();
                    bos = null;
                }
                catch ( IOException ignore )
                {
                }
            }
            if ( fos != null )
            {
                try
                {
                    fos.close();
                    fos = null;
                }
                catch ( IOException ignore )
                {
                }
            }

            if ( zis != null )
            {
                try
                {
                    zis.close();
                    zis = null;
                }
                catch ( IOException ignore )
                {
                }
            }

            if ( fis != null )
            {
                try
                {
                    fis.close();
                    fis = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return unzipFile;
    }

    public static String getTimeAsString()
    {
        s_calendar = Calendar.getInstance();

        int today = s_calendar.get( Calendar.DAY_OF_MONTH );
        int thisMonth = s_calendar.get( Calendar.MONTH ) + 1;
        int thisYear = s_calendar.get( Calendar.YEAR );
        int thisHour = s_calendar.get( Calendar.HOUR_OF_DAY );
        int thisMin = s_calendar.get( Calendar.MINUTE );
        int thisSecond = s_calendar.get( Calendar.SECOND );
		int thisMilliSecond = s_calendar.get( Calendar.MILLISECOND );

        return thisMonth + "-" + today + "-" + thisYear + "-" + thisHour + "-" + thisMin + "-" + thisSecond + "-" + thisMilliSecond;
		//return thisMonth + "-" + today + "-" + thisYear + "-" + thisHour + "-" + thisMin + "-" + thisSecond ;
    }

    public static Message[] getAllPOP3InboxMessages( String host, String username, String password) throws Exception
    {
        Session session = null;

        //Getting the System properties
        Properties sysProperties = System.getProperties();

        //store the protocol pop3
        sysProperties.put("mail.protocol.store", POP_MAIL );

        //Get the Default session Object
        session = Session.getDefaultInstance(sysProperties, null);

        session.setDebug(false);

        //Get the Store Object that user's desired store protocol.
        //If appropriate store object is not obtained, No SuchProvider Exception is Thrown
        Store store = session.getStore(POP_MAIL);

        //Connects the Mail Server
        store.connect(host, username, password);
        log("Successfully logged in to " + host + "\n");
        System.out.println("Successfully logged in to " + host + "\n");

        Folder folder = store.getDefaultFolder();

        if (folder == null)
        {
            throw new ScalarException("No default mail folder");
        }
        //Get the Inbox folder
        folder = folder.getFolder(INBOX);
        if (folder == null)
        {
            throw new ScalarException("Unable to get folder: " + folder);
        }
        //Opens the folder and set the field to read write mode
        folder.open(Folder.READ_WRITE);

        //Get the Messages
        return folder.getMessages();
    }

    //Append FileName parameter is Used When the attached File Name is Not Proper(or when attached filenames are same for two mails)
    public static void readLatestMessage( int m_adaptor_id, Message[] message, String subject, String outputDir, String fileType, String appendFileName ) throws Exception
    {
        Message wipMessage  = null;
        if ( message == null || message.length == 0 )
        {
            return;
        }
        BodyPart part = null;
        Multipart mp  = null;
        /*To download Wip sheet */
        for (int i = 0; i < message.length; i++)
        {
            //To get the only  : WIP Report with subject
			if ( message[i].getSubject() != null && message[i].getSubject().trim().length() > 0
                    && ( message[i].getSubject().startsWith( subject ) || message[i].getSubject().endsWith( subject ) || message[i].getSubject().indexOf(subject) != -1  ) )
            {
                Object obj = message[i].getContent();

                if ( wipMessage == null )
                {
                    if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                    {
                         wipMessage = message[i];
                    }
                    else
                    {
                        if (obj instanceof Multipart )
                        {
                           mp = (Multipart) obj;

                            for ( int m = 0; m < mp.getCount(); m++ )
                            {
                                part = mp.getBodyPart(m);

                                if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( BodyPart.ATTACHMENT ) || part.getDisposition().equals( BodyPart.INLINE ))  )
                                {
                                    wipMessage = message[i];
                                    break;
                                }
                                else if ( part.getFileName() != null )
                                {
                                    wipMessage = message[i];
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    java.util.Date date1 = wipMessage.getSentDate();
                    java.util.Date date2 = null;

                    if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                    {
                         date2 = message[i].getSentDate();
                    }
                    else
                    {
                        if (obj instanceof Multipart )
                        {
                           mp = (Multipart) obj;

                            for ( int m = 0; m < mp.getCount(); m++ )
                            {
                                part = mp.getBodyPart(m);

                                if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( BodyPart.ATTACHMENT ) || part.getDisposition().equals( BodyPart.INLINE ))  )
                                {
                                    date2 = message[i].getSentDate();
                                    break;
                                }
                                else if ( part.getFileName() != null )
                                {
                                    date2 = message[i].getSentDate();
                                    break;
                                }
                            }
                        }
                    }

                    if (date1 != null && date2 != null)
                    {
                        if (date2.compareTo(date1) > 0)
                        {
                            wipMessage = message[i];
                        }
                    }
                }
            }
        }

        // To process the Message and download the files
        if ( wipMessage != null )
        {
            downLoadMessage( m_adaptor_id, wipMessage, subject, outputDir, fileType, appendFileName );
            wipMessage = null;
        }
        else
        {
             log("\n\n****The Requested Subject was not found in INBOX***" + subject + "\n");
             System.out.println("\n\n****The Requested Subject was not found in INBOX***" + subject+"\n" );
        }
    }
    public static Message readLatestMessage( Message[] message, String subject ) throws Exception
    {
        Message wipMessage  = null;
        if ( message == null || message.length == 0 )
        {
            return null;
        }
        BodyPart part = null;
        Multipart mp  = null;
        /*To download Wip sheet */
        for (int i = 0; i < message.length; i++)
        {
            //To get the only  : WIP Report with subject
			if ( message[i].getSubject() != null && message[i].getSubject().trim().length() > 0
                    && ( message[i].getSubject().startsWith( subject ) || message[i].getSubject().endsWith( subject ) || message[i].getSubject().indexOf(subject) != -1  ) )
            {
                Object obj = message[i].getContent();

                if ( wipMessage == null )
                {
                    if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                    {
                         wipMessage = message[i];
                    }
                    else
                    {
                        if (obj instanceof Multipart )
                        {
                           mp = (Multipart) obj;

                            for ( int m = 0; m < mp.getCount(); m++ )
                            {
                                part = mp.getBodyPart(m);

                                if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( BodyPart.ATTACHMENT ) || part.getDisposition().equals( BodyPart.INLINE ))  )
                                {
                                    wipMessage = message[i];
                                    break;
                                }
                                else if ( part.getFileName() != null )
                                {
                                    wipMessage = message[i];
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    java.util.Date date1 = wipMessage.getSentDate();
                    java.util.Date date2 = null;

                    if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                    {
                         date2 = message[i].getSentDate();
                    }
                    else
                    {
                        if (obj instanceof Multipart )
                        {
                           mp = (Multipart) obj;

                            for ( int m = 0; m < mp.getCount(); m++ )
                            {
                                part = mp.getBodyPart(m);

                                if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( BodyPart.ATTACHMENT ) || part.getDisposition().equals( BodyPart.INLINE ))  )
                                {
                                    date2 = message[i].getSentDate();
                                    break;
                                }
                                else if ( part.getFileName() != null )
                                {
                                    date2 = message[i].getSentDate();
                                    break;
                                }
                            }
                        }
                    }

                    if (date1 != null && date2 != null)
                    {
                        if (date2.compareTo(date1) > 0)
                        {
                            wipMessage = message[i];
                        }
                    }
                }

            }
        }

        return wipMessage;

    }

    public static void readLatestDayMessages( int m_adaptor_id, Message[] message, String subject, String outputDir, String fileType, String appendFileName ) throws Exception
    {
        Message wipMessage  = null;
        java.util.Date maxDate = null;
        ArrayList subMessageList = new ArrayList();
        if ( message == null || message.length == 0 )
        {
            return;
        }
        BodyPart part = null;
        Multipart mp  = null;
        /*To download Wip sheet */
        for (int i = 0; i < message.length; i++)
        {
            //To get the only  : WIP Report with subject
            if ( message[i].getSubject() != null && message[i].getSubject().trim().length() > 0
                    && ( message[i].getSubject().startsWith( subject ) || message[i].getSubject().endsWith( subject ) || message[i].getSubject().indexOf(subject) != -1  ) )
            {
                subMessageList.add(message[i]);
                Object obj = message[i].getContent();
                if ( wipMessage == null )
                {
                    if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                    {
                         wipMessage = message[i];
                         maxDate = wipMessage.getSentDate();
                    }
                    else
                    {
                        if (obj instanceof Multipart )
                        {
                           mp = (Multipart) obj;

                            for ( int m = 0; m < mp.getCount(); m++ )
                            {
                                part = mp.getBodyPart(m);

                                if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( BodyPart.ATTACHMENT ) || part.getDisposition().equals( BodyPart.INLINE ))  )
                                {
                                    wipMessage = message[i];
                                    maxDate = wipMessage.getSentDate();
                                    break;
                                }
                                else if ( part.getFileName() != null )
                                {
                                    wipMessage = message[i];
                                    maxDate = wipMessage.getSentDate();
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    java.util.Date date1 = wipMessage.getSentDate();
                    java.util.Date date2 = null;

                    if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                    {
                         date2 = message[i].getSentDate();
                    }
                    else
                    {
                        if (obj instanceof Multipart )
                        {
                           mp = (Multipart) obj;

                            for ( int m = 0; m < mp.getCount(); m++ )
                            {
                                part = mp.getBodyPart(m);

                                if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( BodyPart.ATTACHMENT ) || part.getDisposition().equals( BodyPart.INLINE ))  )
                                {
                                    date2 = message[i].getSentDate();
                                    break;
                                }
                                else if ( part.getFileName() != null )
                                {
                                    date2 = message[i].getSentDate();
                                    break;
                                }
                            }
                        }
                    }
                    if (date1 != null && date2 != null)
                    {
                        if (date2.compareTo(date1) > 0)
                        {
                            maxDate = date2;
                        }
                    }
                }
            }
        }

        Calendar cal = Calendar.getInstance();
        if ( maxDate != null )
        {
            cal.setTime( maxDate );
            cal.add( Calendar.DAY_OF_MONTH, -1);
        }
        
        for (int i = 0; i < subMessageList.size(); i++)
        {
            wipMessage = (Message)subMessageList.get(i);

            java.util.Date date1 = StringUtils.format(StringUtils.formatDateToString( cal.getTime(), "MM/dd/yyyy") );
            java.util.Date date2 = StringUtils.format(StringUtils.formatDateToString(wipMessage.getSentDate(), "MM/dd/yyyy") );
            if (date1 != null && date2 != null)
            {
                if (date2.compareTo(date1) >=0)
                {
                    // To process the Message and download the files
                    if ( wipMessage != null )
                    {
                        downLoadMessage( m_adaptor_id, wipMessage, subject, outputDir, fileType, appendFileName );
                    }
                }
            }
        }
    }

    /**
     * To DownLoad the sheet
     * and save the File in to out side the Done Directory
     *
     * @param message
     * @throws Exception
     */
    public static void downLoadMessage( int m_adaptor_id , Message message, String subject , String outputDir, String fileType, String appendFileName) throws Exception
    {
        if ( message == null )
        {
            return;
        }

        Multipart mp        = null;
        BodyPart part           = null;
        String disposition  = null;
        InputStream inputStream = null;

        String fileName     = null;
        String fileExtn    = null;
        log("Processing  Message for "+ subject + " .......");
        System.out.println("Processing  Message for "+ subject + " .......");

        try
        {
            //IF BLOCK EXECUTES ONLY FOR OSE WIP FILE
            if ( message.getDisposition() != null && ( message.getDisposition().equals( Message.ATTACHMENT ) || message.getDisposition().equals( Message.INLINE ) ) && message.getFileName() != null )
            {
                fileName = message.getFileName().replaceAll("\\?", "").replaceAll("=5F=5F", "_").replaceAll("=2E", ".");
                String messgaeFileName = fileName;
                if ( fileName.indexOf("PCCWIPSTD") != -1 )
                {
                    fileName =  fileName.substring( fileName.indexOf("PCCWIPSTD") , fileName.lastIndexOf(".") );
                    fileExtn  = messgaeFileName.substring( messgaeFileName.lastIndexOf(".") + 1 , messgaeFileName.length() );
                }
                else
                {
                   fileName =  fileName.substring( 0 , fileName.lastIndexOf(".") );
                   fileExtn  = messgaeFileName.substring( messgaeFileName.lastIndexOf(".") + 1 , messgaeFileName.length() );
                }
                //System.out.println("fileExtn = " + fileExtn);
                inputStream = message.getInputStream();
				if ( fileName != null )
				{
					fileName = fileName.toUpperCase();

					if ( m_adaptor_id > 0 )
					{
						AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , fileName, fileExtn, StringUtils.formatDateToString( message.getSentDate(), "MM/dd/yyyy HH:mm:ss") ) ;
					}
					if ( appendFileName != null )
					{											
						fileName = appendFileName +"_" + fileName;
					}
					log("\tDownloding "+subject+"................. ");
					System.out.println("\tDownloding "+subject+"................. ");

					saveAsBinaryFile( new BufferedInputStream(inputStream), outputDir, fileName, fileExtn, true /* append time stamp */);
					System.out.println("Done.\n"  );
					fileName = null;
				}
              
            }
            else
            {
                Object obj = message.getContent();

                if (obj instanceof Multipart )
                {
                    mp = (Multipart) obj;

                    for ( int i = 0; i < mp.getCount(); i++ )
                    {
                        part = mp.getBodyPart(i);

                        disposition = part.getDisposition();
                        
                        //taking the wip & ASSEMBLY attachmentS
                        if ( ( disposition != null ) && ( disposition.equals( BodyPart.ATTACHMENT ) || disposition.equals( BodyPart.INLINE ))  )
                        {
                            if ( part.getFileName() != null && part.getFileName().toUpperCase().indexOf("PDF") < 1 )
                            {
                                if ( "summary".equalsIgnoreCase(fileType) )
                                {
                                      fileExtn = FILE_EXTN_TXT;
                                }
                                if ("IKANOS CP DATA".equalsIgnoreCase( subject ) )
                                {
                                    if ( part.getFileName().indexOf("sum.txt") != -1 )
                                    {
                                        fileName =  part.getFileName().substring( 0 , part.getFileName().lastIndexOf(".") );
                                        fileExtn  = part.getFileName().substring( part.getFileName().lastIndexOf(".") + 1 , part.getFileName().length() );
                                    }
                                }
                                else
                                {
                                    fileName =  part.getFileName().substring( 0 , part.getFileName().lastIndexOf(".") );
                                    fileExtn  = part.getFileName().substring( part.getFileName().lastIndexOf(".") + 1 , part.getFileName().length() );
                                }
                                
                                inputStream = part.getInputStream();

                                if ( fileName != null && fileName.indexOf("Legend Silicon Daily Transaction report") == -1 )
                                {
                                    fileName = fileName.replaceAll("-", "_").toUpperCase().replaceAll("LEGEND", "L").replaceAll("SILICON", "S").replaceAll("INVENTORY", "INV");

                                    if ( m_adaptor_id > 0 )
                                    {
                                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , fileName, fileExtn, StringUtils.formatDateToString( message.getSentDate(), "MM/dd/yyyy HH:mm:ss") ) ;
                                    }

                                    if ( appendFileName != null )
                                    {											
                                        fileName = appendFileName +"_" + fileName;
                                    }

                                    log("\tDownloding "+subject+"................. ");
                                    System.out.println("\tDownloding "+subject+"................. ");

                                    saveAsBinaryFile( new BufferedInputStream(inputStream), outputDir, fileName, fileExtn, true /* append time stamp */);
                                    fileName = null;
                                    System.out.println("Done.\n"  );
                                }
                            }
                        }
                    } //FOR LOOP
                }//IF FOR CHECKING ONLY MULTI PART      
            }
        }
        catch( Exception e)
        {
            System.out.println("EXception Occcuered while Proceess and downloading the Messge:" + e );
            e.printStackTrace();
            throw e;
        }
        finally
        {
            if ( inputStream != null )
            {
                try
                {
                    inputStream.close();
                    inputStream = null;
                }
                catch (IOException e)
                {
                }
            }
        }
    }

    public static void fileCopy( String sourceFile, String destFile ) throws IOException
    {

        if ( ( sourceFile == null ) || ( destFile == null ) )
        {
            return;
        }

        File inputFile = new File( sourceFile );
        File outputFile = new File( destFile );

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try
        {

            fis = new FileInputStream( inputFile );
            fos = new FileOutputStream( outputFile );
            byte[] buf = new byte[1024];
            int i = 0;
            while ( ( i = fis.read( buf ) ) != -1 )
            {
                fos.write( buf, 0, i );
            }
        }
        finally
        {
            if ( fis != null )
                try
                {
                    fis.close();
                }
                catch ( IOException ignore )
                {
                    throw ignore;
                }
            if ( fos != null )
                try
                {
                    fos.close();
                }
                catch ( IOException ignore )
                {
                    throw ignore;
                }
        }

    }

    public static void moveFilesToDone( ArrayList successFileList, File doneDestDir ) throws IOException
    {
       String tempFileName = null;
       String tempDestFileName = null;
       File tempFile = null;
       int successFileListSize = successFileList.size();

       for (int i = 0; i < successFileListSize; i++)
       {
           tempFile         = (File) successFileList.get(i);
           tempFileName     = tempFile.getAbsolutePath();
           tempDestFileName = doneDestDir.getAbsolutePath() + "/" + tempFile.getName();

           fileCopy(tempFileName, tempDestFileName);

           if ( tempFile.delete() == false )
           {
               log("WARNING!! WARNING!! WARNING!! Copied " + tempFile.getName() + " to " + doneDestDir.getAbsolutePath() + ", but Could not delete it from the present directory ");
           }
           else
           {
               log(tempFile.getName() + " has been moved to " + doneDestDir.getAbsolutePath());
           }
       }
    }

    public static void printHeader(String vendor, String type)
    {
        String s = ("\n\n+----------- Running "+ vendor +" " + type +" on " + new java.util.Date(System.currentTimeMillis()) + " -------------+\n" +
                "\n+---------------------------------------------------------------+\n" +
                "+                                                                \n" +
                "+                     "+ vendor +" " + type +" - Beta            \n" +
                "+                                                                \n" +
                "+    Copy Right (C) - ScalarSoft Inc., All rights reserved.      \n" +
                "+                                                                \n" +
                "+---------------------------------------------------------------+\n");
        System.out.println(s);
        log(s);
    }
    public static void makeAllAdaptorDirs( String outPutDirName) throws ScalarException
    {
        if ( outPutDirName != null )
        {
            File tempLocalOutDir = new File( outPutDirName );
            if ( !tempLocalOutDir.exists() )
            {
                if ( !tempLocalOutDir.mkdirs() )
                {
                    throw new ScalarException( "Parser: Could not create " + outPutDirName );
                }
            }

            if ( !tempLocalOutDir.exists() )
            {
                System.out.println(tempLocalOutDir + " directory doesnt exist");
                return;
            }

            if ( !tempLocalOutDir.isDirectory() )
            {
                System.out.println(tempLocalOutDir + " is not a directory");
                return;
            }

            if ( !tempLocalOutDir.canRead() )
            {
                System.out.println(tempLocalOutDir + " not readable");
                return;
            }
        }

        String m_doneOutputDir      = null;
        String m_logOutputDir       = null;
        String m_removeOutputDir    = null;

        m_logOutputDir   =  outPutDirName  + "/logs";
        m_doneOutputDir  =  outPutDirName  + "/done";
        m_removeOutputDir=  outPutDirName  + "/removed";

        File doneDestDir = new File( m_doneOutputDir );
        if ( doneDestDir.exists() == false )
        {
            doneDestDir.mkdirs();
        }
        File logDestDir = new File( m_logOutputDir );
        if ( logDestDir.exists() == false )
        {
            logDestDir.mkdirs();
        }
        
        File removeDestDir = new File( m_removeOutputDir );
        if ( removeDestDir.exists() == false )
        {
            removeDestDir.mkdirs();
        }
    }

    public static Logger getAdaptorLogger( String outPutDirName, String vendorName) throws ScalarException
    {
         if ( adaptorLogger == null )
         {
             adaptorLogger = new Logger( outPutDirName + "/logs",
                                             vendorName.toLowerCase()+"_"+ ADAPTOR_LOG_FILE_NAME,
                                             vendorName.toUpperCase()+"."+ ADAPTOR_LOG_PREFIX,
                                             LOG_LEVEL,
                                             MAX_LOG_FILE_SIZE,
                                             ROTATING_LOG_FILE_COUNT );
         }
         return adaptorLogger;
    }

    public static Logger getDataParserLogger( String outPutDirName, String vendorName) throws ScalarException
    {
         if ( parserLogger == null )
         {
             parserLogger = new Logger( outPutDirName + "/logs",
                                             vendorName.toLowerCase()+"_"+ DATA_PARSER_LOG_FILE_NAME,
                                             vendorName.toUpperCase()+"."+ DATA_PARSER_LOG_PREFIX,
                                             LOG_LEVEL,
                                             MAX_LOG_FILE_SIZE,
                                             ROTATING_LOG_FILE_COUNT );
         }
         return parserLogger;
   }

    /**
     * Sends email notifying about data parsing errors
     *
     * @param errors List of all parser errors (Included in message body)
     * @param fileToBeAttached to be sent with the mail as an attachment
     */
    public static void notifyAdaptorDataParsingErrors( ArrayList errors, String fileToBeAttached )
    {
        try
        {
            String from = ConfigManager.getSysAdminEmail();
            String to = NotificationSetupDAO.loadAdaptorNotificationSubscriberEmails();
            String subject = "ATTENTION!! ATTENTION!! ATTENTION!! Adaptor Parser errors";

            StringBuffer errorDesc = new StringBuffer();
            int size = errors.size();
            for ( int i = 0; i < size; i++ )
            {
                errorDesc.append( "<li>" + errors.get( i ) + "\n<br>" );
            }

            String message = "<html><body><center><h2><u>Adaptor Data Parser Errors</u></h2></center>" +
                    "<p>Encountered Exceptions while parsing the adaptor data." +
                    "The data file is attached with this mail. Errors are listed down here:</p>" +
                    errorDesc.toString() + "<br><br></body></html>";

            Mailer.send( from, to, null/*cc*/, null/*bcc*/, subject, message, new String[]{fileToBeAttached}, Mailer.CONTENT_TYPE_HTML );
        }
        catch ( Exception mailException )
        {

            System.out.println( "***** ATTENTION - PARSER ERROR *****\n" );
            System.out.println( "Couldnt send mail: " + mailException.getMessage() + "\n" );

            int size = errors.size();
            for ( int i = 0; i < size; i++ )
            {
                System.out.println( "Error(" + i + ") : " + errors.get( i ) + "\n" );
            }
        }
    }

    public static Logger getJobHandlerLogger() throws ScalarException
    {
        File outDir = null;
        outDir = new File ( ConfigManager.getLogDirectory() );
        if ( outDir.exists() == false )
        {
            outDir.mkdirs();
        }

        if ( jobHandlerLogger == null)
        {
            jobHandlerLogger =  new Logger( ConfigManager.getLogDirectory(),
                                            JOB_SCHEDULING_LOG_FILE_NAME,
                                            JOB_SCHEDULING_LOG_PREFIX,
                                            LOG_LEVEL,
                                            MAX_LOG_FILE_SIZE_JOB_HANDLER,
                                            ROTATING_LOG_FILE_COUNT );
        }
        return  jobHandlerLogger;
    }

    public static Logger getWIPFEDAdaptorLogger() throws ScalarException
    {
        if (wipFedAdaptorLogger  == null)
        {
            wipFedAdaptorLogger = new Logger( getWipFedDataOutputDir() + "/logs",
                                                WIPFED_ADAPTOR_LOG_FILE_NAME,
                                                WIPFED_ADAPTOR_LOG_PREFIX,
                                                LOG_LEVEL,
                                                MAX_LOG_FILE_SIZE,
                                                ROTATING_LOG_FILE_COUNT);
        }

        return wipFedAdaptorLogger;
    }
    public static Logger getWIPFEDParserLogger() throws ScalarException
    {
        if (wipFedParserLogger == null)
        {
            wipFedParserLogger = new Logger( getWipFedDataOutputDir() + "/logs",
                                                WIPFED_DATA_PARSER_LOG_FILE_NAME,
                                                WIPFED_DATA_PARSER_LOG_PREFIX,
                                                LOG_LEVEL,
                                                MAX_LOG_FILE_SIZE,
                                                ROTATING_LOG_FILE_COUNT);
        }

        return wipFedParserLogger;
    }

    public static Logger getWIPFEDSortAdaptorLogger() throws ScalarException
    {
        if (wipFedAdaptorLogger  == null)
        {
            wipFedAdaptorLogger = new Logger( getWipFedSortDataOutputDir() + "/logs",
                                                WIPFED_ADAPTOR_LOG_FILE_NAME,
                                                WIPFED_ADAPTOR_LOG_PREFIX,
                                                LOG_LEVEL,
                                                MAX_LOG_FILE_SIZE,
                                                ROTATING_LOG_FILE_COUNT);
        }

        return wipFedAdaptorLogger;
    }
    public static Logger getWIPFEDSortParserLogger() throws ScalarException
    {
        if (wipFedParserLogger == null)
        {
            wipFedParserLogger = new Logger( getWipFedSortDataOutputDir() + "/logs",
                                                WIPFED_DATA_PARSER_LOG_FILE_NAME,
                                                WIPFED_DATA_PARSER_LOG_PREFIX,
                                                LOG_LEVEL,
                                                MAX_LOG_FILE_SIZE,
                                                ROTATING_LOG_FILE_COUNT);
        }

        return wipFedParserLogger;
    }

    public static String getDataOutputDir(String vendorName, String Location) throws ScalarException
    {

        VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( vendorName, Location );

        String dataOutDir = null;
        try
        {
            String accountNumber = vendorAdaptor.getCustomerId();
            String dataDir = vendorAdaptor.getOutPutDirectory();
            String userId = vendorAdaptor.getUserId();
            if ( userId != null ) userId = userId.trim();

            if ( dataDir != null )
            {
                if ( dataDir.endsWith( "/" ) || dataDir.endsWith( "\\" ) )
                {
                    dataOutDir = dataDir + userId;
                }
                else
                {
                    dataOutDir = dataDir + "/" + userId;
                }
            }
        }
        catch ( Exception e )
        {
            System.out.println( "*****ERROR!! ERROR!! Exception while loading Adaptor Username, Password details from database:********* \n\n" );
            e.printStackTrace();
        }
        return dataOutDir;
    }

    public static String getWipFedDataOutputDir() throws ScalarException
    {
        String dataOutDir = null;

        dataOutDir = ConfigManager.getWipFedSheetDirectory();

        if( dataOutDir == null || dataOutDir.trim().length() == 0 )
        {
            throw new ScalarException( "ERROR!! ERROR!! ERROR!! Could not find Adaptor Out Directory " );
        }

        File wipFedDestDir = new File( dataOutDir );
        if (wipFedDestDir.exists() == false)
        {
           wipFedDestDir.mkdirs();
        }
        dataOutDir = wipFedDestDir.getAbsolutePath();

        return dataOutDir;
    }

    public static String getWipFedSortDataOutputDir() throws ScalarException
        {
            String dataOutDir = null;

            dataOutDir = ConfigManager.getWipFedSortSheetDirectory();

            if( dataOutDir == null || dataOutDir.trim().length() == 0 )
            {
                throw new ScalarException( "ERROR!! ERROR!! ERROR!! Could not find Adaptor Out Directory " );
            }

            File wipFedDestDir = new File( dataOutDir );
            if (wipFedDestDir.exists() == false)
            {
               wipFedDestDir.mkdirs();
            }
            dataOutDir = wipFedDestDir.getAbsolutePath();

            return dataOutDir;
        }


     /**
     * Returns an equivalent valeu to Java month for a given month name
     * BR - June 03, 2004
     */
    public static int getJavaCalendarMonth( String month )
    {
        int javaMonth = -1;

        if ( ( month == null ) || ( month.trim().length() == 0 ) )
        {
            return javaMonth;
        }

        month = month.toLowerCase();

        if ( month.startsWith( "jan" ) )
        {
            javaMonth = 0;
        }
        else if ( month.startsWith( "feb" ) )
        {
            javaMonth = 1;
        }
        else if ( month.startsWith( "mar" ) )
        {
            javaMonth = 2;
        }
        else if ( month.startsWith( "apr" ) )
        {
            javaMonth = 3;
        }
        else if ( month.startsWith( "may" ) )
        {
            javaMonth = 4;
        }
        else if ( month.startsWith( "jun" ) )
        {
            javaMonth = 5;
        }
        else if ( month.startsWith( "jul" ) )
        {
            javaMonth = 6;
        }
        else if ( month.startsWith( "aug" ) )
        {
            javaMonth = 7;
        }
        else if ( month.startsWith( "sep" ) )
        {
            javaMonth = 8;
        }
        else if ( month.startsWith( "oct" ) )
        {
            javaMonth = 9;
        }
        else if ( month.startsWith( "nov" ) )
        {
            javaMonth = 10;
        }
        else if ( month.startsWith( "dec" ) )
        {
            javaMonth = 11;
        }

        return javaMonth;
    }


    public static void convertXLStoHTML(String fileName, String dataDir, String newFileName) throws ScalarException
    {
         try
        {
            Runtime rt = Runtime.getRuntime();
            
            String cmd = ConfigManager.getConvertionXLStoHTMLName()+" "+ fileName;

            Process proc = rt.exec(cmd);
            try
            {
                BufferedReader reader = null;
                reader = new BufferedReader( new InputStreamReader( proc.getInputStream() ) );
                String outputFile = AdaptorUtils.saveAsFile(reader, dataDir, newFileName, AdaptorUtils.FILE_EXTN_HTML);
            }
            catch (IOException ioe)
            {
                ioe.printStackTrace();
            }
            int exitVal = proc.waitFor();
            //System.out.println("ExitValue: " + exitVal);
        }
        catch (Throwable t)
        {
            t.printStackTrace();
        }
    }

    public static String getWaferIDsByFormat(String wafers)
    {
        String waferId  = "";
        int startWafer  = 0;
        int endWafer    = 0;
        String waferArray[] = null;
        String waferIds[]   = null;

        if (wafers == null)
        {
            return null;
        }

        wafers = wafers.replace('.', ',');

        if (wafers.indexOf("-") == -1)
        {
            if (wafers.indexOf(",") == -1)
            {
                try
                {   
                    waferId = Integer.parseInt(wafers.trim()) + ";";
                }
                catch (Exception e)
                {
                    log("Number Format Exception when formatting wafers " + wafers);
                    waferId = wafers;
                }

                return waferId;
            }
            else
            {
                waferArray = wafers.split(",");

                for (int i = 0; i < waferArray.length; i++)
                {
                    try
                    {
                        waferId += Integer.parseInt(waferArray[i].trim() ) + ";";
                    }
                    catch (Exception e)
                    {
                        log("Number Format Exception when formatting wafers" + wafers);
                        waferId = wafers;
                    }
                }

                return waferId;
            }
        }
        else
        {
            waferIds = wafers.split(",");
            
            for (int i = 0; i < waferIds.length; i++)
            {
                if (waferIds[i].trim().indexOf("-") == -1)
                {
                    try
                    {
                        waferId += Integer.parseInt(waferIds[i].trim()) + ";";
                    }
                    catch (Exception e)
                    {
                        log("Number Format Exception when formatting wafers" + wafers);
                        waferId = wafers;
                    }
                }
                else
                {

                    try
                    {
                        if (waferIds[i].replaceAll(";","").trim().length() == 5)
                        {
                            startWafer = Integer.parseInt(waferIds[i].trim().substring(0, 2));
                            endWafer = Integer.parseInt(waferIds[i].trim().substring(3, 5));
                        }
                        if (waferIds[i].replaceAll(";","").trim().length() == 4)
                        {
                            startWafer = Integer.parseInt(waferIds[i].trim().substring(0, 1));
                            endWafer = Integer.parseInt(waferIds[i].trim().substring(2, 4));
                        }

                        if (waferIds[i].replaceAll(";","").trim().length() == 3)
                        {
                            startWafer = Integer.parseInt(waferIds[i].trim().substring(0, 1));
                            endWafer = Integer.parseInt(waferIds[i].trim().substring(2, 3));
                        }
                    }
                    catch (Exception e)
                    {
                        log("Number Format Exception when formatting wafers" + wafers);
                        waferId = wafers;
                    }
                    for (int j = startWafer; j <= endWafer; j++)
                    {
                        if (j != 0 )
                        {
                            waferId += j + ";";
                        }   
                    }
                }
            }
            return waferId;
        }
    }
    private static void log (String message)
    {
        if (message == null) return;

        if (s_logger != null)
        {
            synchronized(s_logger)
            {
               s_logger.logDebug (message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println (message);
        }
    }

    public static void setLogger (Logger logger)
    {
        s_logger = logger;
    }
    
    public static void main( String[] args ) throws Exception
    {
        System.out.println( "AAMKOR Assembly data output dir = " );
    }

}